package com.maker.mcp.server.tool;

import com.maker.mcp.server.entity.Email;
import com.maker.mcp.server.utils.MakerUtil;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import jakarta.mail.MessagingException;
import org.springframework.stereotype.Component;


@Component
@Slf4j
/**
 * 邮件发送服务
 * 例如：
 * 1、请写一份北京2日游的旅游攻略，发送到邮箱zhaokaoyan2012@163.com
 * 2、请用好看的css+html写一个从北京市朝阳区小红门到大红门的乘车路线的页面，再把完整的HTML页面内容发送到我的邮箱里
 * 3.请用markdown格式写一个从北京市朝阳区小红门到大红门的乘车路线的页面，再把完整的内容发送到我的邮箱里
 * 4.请用好看的css+html编写一份北京1日游攻略，文件输出到D:/java_project/mcp-file-path-test，文件名为maker.html。如果文件已存在，则覆盖，在把文件内容发送到我的邮箱里
 */
public class EmailTool {

    private final JavaMailSender mailSender;
    private final String from;
    @Autowired
    public EmailTool(JavaMailSender mailSender,
                     @Value("${spring.mail.username}") String from) {
        this.mailSender = mailSender;
        this.from = from;
    }

    @Tool(description = "给指定的邮箱发送邮件信息，email为收件人有限，subject为邮件标题或主题，message为邮件内容")
    public void sendMailMessage(Email email){

        log.info("=============调用MCP工具：sendMailMessage=============");
        log.info(String.format("参数Email：%s", email.toString()));
        Integer contentType = email.getContentType();
        log.info(String.format("=============参数contentType：%s", contentType));

        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);
            helper.setTo(email.getEmail());
            helper.setSubject(email.getSubject());
            if(contentType == 1){
                helper.setText(MakerUtil.convertToHtml(email.getMessage()), true);
            }else if(contentType == 2){
                helper.setText(email.getMessage(),true);
            }else{
                helper.setText(email.getMessage());
            }
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("邮件发送失败：{}", e.getMessage());
        }

    }

    @Tool(description = "查询我的邮箱地址或邮件")
    public String getMyEmailAddress(){
        log.info("=============调用MCP工具：getMyEmailAddress=============");

        //结合实际的业务场景，可以根据用户ID去数据库里查询到邮箱信息

        return "zhaokaoyan2012@163.com";
    }




}
